"""
商品查询任务处理模块
负责处理客户查询商品信息的请求
"""

import logging
import re
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)

class ProductQueryTask:
    """商品查询任务处理器"""
    
    def __init__(self):
        self.task_name = "查询商品信息"
        self.logger = logging.getLogger(f"{__name__}.ProductQueryTask")
    
    def can_handle(self, message: str, conversation_history: list) -> bool:
        """
        判断是否可以处理此消息
        
        Args:
            message: 客户消息
            conversation_history: 对话历史
            
        Returns:
            bool: 是否可以处理
        """
        # 商品查询关键词
        product_keywords = [
            '商品', '产品', '物品', '东西', '货', '商品信息', '产品信息',
            '什么', '哪个', '哪种', '介绍', '说明', '详情', '规格',
            '价格', '多少钱', '费用', '成本', '价值'
        ]
        
        # 检查是否包含商品查询关键词
        for keyword in product_keywords:
            if keyword in message:
                return True
        
        # 检查是否是商品名称（简单判断）
        if self._is_product_name(message):
            return True
            
        return False
    
    def _is_product_name(self, message: str) -> bool:
        """判断是否是商品名称"""
        # 商品名称特征
        product_patterns = [
            r'[A-Za-z]+',  # 英文商品名
            r'[红黄蓝绿紫黑白灰]色?',  # 颜色
            r'[毛衣|衣服|裤子|鞋子|帽子|包|手机|电脑|书|笔]',  # 常见商品
        ]
        
        for pattern in product_patterns:
            if re.search(pattern, message):
                return True
        return False
    
    def process(self, message: str, conversation_history: list, customer_id: str) -> Dict[str, Any]:
        """
        处理商品查询任务
        
        Args:
            message: 客户消息
            conversation_history: 对话历史
            customer_id: 客户ID
            
        Returns:
            Dict: 处理结果
        """
        self.logger.info(f"🛍️ 开始处理商品查询任务 - 客户: {customer_id}")
        self.logger.info(f"📝 客户消息: {message}")
        
        try:
            # 提取商品信息
            product_info = self._extract_product_info(message)
            
            # 生成回复
            response = self._generate_response(product_info, message)
            
            # 记录处理结果
            result = {
                "task_type": self.task_name,
                "success": True,
                "product_info": product_info,
                "response": response,
                "customer_id": customer_id,
                "message": message
            }
            
            self.logger.info(f"✅ 商品查询任务处理完成 - 提取信息: {product_info}")
            return result
            
        except Exception as e:
            self.logger.error(f"❌ 商品查询任务处理失败: {str(e)}")
            return {
                "task_type": self.task_name,
                "success": False,
                "error": str(e),
                "response": "抱歉，商品信息查询出现异常，请稍后再试。"
            }
    
    def _extract_product_info(self, message: str) -> Dict[str, str]:
        """提取商品信息"""
        product_info = {
            "name": "",
            "color": "",
            "category": "",
            "description": ""
        }
        
        # 提取颜色信息
        colors = ['红色', '黄色', '蓝色', '绿色', '紫色', '黑色', '白色', '灰色', '粉色', '橙色']
        for color in colors:
            if color in message:
                product_info["color"] = color
                break
        
        # 提取商品名称
        # 这里可以根据实际需求扩展商品识别逻辑
        if "毛衣" in message:
            product_info["name"] = "毛衣"
            product_info["category"] = "服装"
        elif "手机" in message:
            product_info["name"] = "手机"
            product_info["category"] = "电子产品"
        elif "电脑" in message:
            product_info["name"] = "电脑"
            product_info["category"] = "电子产品"
        else:
            # 提取可能的商品名称
            words = message.split()
            for word in words:
                if len(word) >= 2 and not word.isdigit():
                    product_info["name"] = word
                    break
        
        # 生成描述
        if product_info["name"] and product_info["color"]:
            product_info["description"] = f"{product_info['color']}{product_info['name']}"
        elif product_info["name"]:
            product_info["description"] = product_info["name"]
        else:
            product_info["description"] = "商品信息"
        
        return product_info
    
    def _generate_response(self, product_info: Dict[str, str], original_message: str) -> str:
        """生成回复内容"""
        if not product_info["name"]:
            return f"您提到的商品信息是：{original_message}，颜色未提及。"
        
        if product_info["color"]:
            return f"您提供的商品信息是：{product_info['name']}，颜色为{product_info['color']}。"
        else:
            return f"您提供的商品信息是：{product_info['name']}，颜色未提及。"
    
    def get_task_summary(self) -> str:
        """获取任务摘要"""
        return f"📊 商品查询任务统计：\n- 任务名称：{self.task_name}\n- 处理状态：正常" 